package net.qanar.gwnewsfeed.feed.swing;

import java.awt.*;
import java.net.*;

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;

import net.qanar.gwnewsfeed.*;
import net.qanar.gwnewsfeed.feed.*;

public class ItemPanel extends JPanel implements HyperlinkListener{
	static final long serialVersionUID = 123456789;	
	
	private JLabel title;
	private JLabel date;
	private JLabel source;
	private JTextPane content;
	private JScrollPane scrollPane;
	
	{
		this.setPreferredSize(new Dimension(475,525));
		this.setLayout(new FlowLayout (FlowLayout.CENTER, 5, 5));
		
		title = new JLabel("", JLabel.CENTER);
		title.setPreferredSize(new Dimension(450, 25));
		title.setFont(new Font(null, Font.BOLD, 18));
		
		date = new JLabel("", JLabel.LEFT);
		date.setPreferredSize(new Dimension(230, 20));
		
		source = new JLabel("", JLabel.RIGHT);
		source.setPreferredSize(new Dimension(230, 20));
		
		content = new JTextPane(); 
		content.setContentType("text/html");
		content.setText("");
		content.setPreferredSize(new Dimension(465, 465));
		content.setEditable(false);
		content.setCaret(new QuietCaret());
		content.addHyperlinkListener(this);
		scrollPane = new JScrollPane(content);
		scrollPane.setPreferredSize(new Dimension(465, 465));
	}
	
	public ItemPanel(){}
	
	public ItemPanel(Item item) {		
		this.add(title);
		this.add(date);
		this.add(source);
		this.add(scrollPane);
	
		title.setText(item.getTitle());
		date.setText(item.getDate().toString());
		source.setText(item.getSource());
		content.setText(item.getContent());
	}
	
	public void update(Item item) {
		title.setText(item.getTitle());
		date.setText(item.getDate().toString());
		source.setText(item.getSource());
		content.setText(item.getContent());
	}

	@Override
	public void hyperlinkUpdate(HyperlinkEvent arg0) {
		if (arg0.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
			if (arg0.getURL() != null)
				Feed.startBrowser(arg0.getURL());
			else {
				if (arg0.getDescription().charAt(0) == '/') {
					try {
						Feed.startBrowser(new URL("http://www.guildwars.com" + arg0.getDescription()));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}				
		}
	}
}

final class QuietCaret extends DefaultCaret
{
	final static long serialVersionUID = 123456789;
	@Override
	protected void adjustVisibility(Rectangle r) {}
}